package local.kexnichi.appengine.gcalfinance.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import local.kexnichi.appengine.gcalfinance.utility.Constants;
import local.kexnichi.appengine.gcalfinance.utility.Utility;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet;
import com.google.common.collect.Lists;

public class ConfigServlet extends AbstractAppEngineAuthorizationCodeServlet {

    private static final long serialVersionUID = -4967055605737046435L;

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {

        // 読み込み
        com.google.api.services.calendar.Calendar baseCalendar = Utility
                .loadCalendarClient();
        List<String[]> calendarList = getCalendarList(baseCalendar);

        // レスポンス内容の構築
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        StringBuilder contents = new StringBuilder();
        contents.append("<!DOCTYPE html>");
        contents.append("<html><head>");
        contents.append("<meta charset=\"UTF-8\" />");
        contents.append("<title>GCalFinance</title>");
        contents.append("<meta name=\"viewport\" content=\"width=device-width, initital-scale=1\" />");
        contents.append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />");
        contents.append("<link rel=\"apple-touch-icon\" href=\"/img/icon.png\" />");
        contents.append("<link rel=\"shortcut icon\" href=\"/img/favicon.ico\" />");
        contents.append("<link rel=\"stylesheet\" href=\"//ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css\" />");
        contents.append("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"></script>");
        contents.append("<script src=\"//ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js\"></script>");
        contents.append("</head><body>");
        contents.append("<div data-role=\"page\" id=\"config\" data-add-back-btn=\"true\" data-fullscreen=\"true\">");
        contents.append("<header id=\"config_header\" data-role=\"header\" data-position=\"fixed\">");
        contents.append("<h1>Category Select</h1>");
        contents.append("</header>");
        contents.append("<div id=\"config_content\" data-role=\"content\" style=\"margin:45px 0px 40px 0px;\">");
        contents.append("<h1>表示用ページの作成</h1><p>カテゴリとして利用するカレンダーを選択して、表示用ページを作成します。</p>");
        contents.append("<form action=\"/auth/main\" method=\"GET\" data-ajax=\"false\" >");
        contents.append("<fieldset data-role=\"controlgroup\" >");
        for (String[] calendar : calendarList) {
            String calendarid = calendar[Constants.CALENDAR_ID];
            contents.append("<input type=\"checkbox\" name=\"calendarid\" id=\""
                    + calendarid + "\" value=\"" + calendarid + "\" />");
            contents.append("<label for=\"" + calendarid + "\">");
            contents.append(calendar[Constants.CALENDAR_SUMMARY]);
            contents.append("</label>");
        }
        contents.append("</fieldset>");
        contents.append("<input type=\"submit\" value=\"決定\">");
        contents.append("</form>");
        contents.append("</div>");
        contents.append("<footer id=\"config_footer\" data-role=\"footer\" data-position=\"fixed\">");
        contents.append("<h5>Copyright &copy; 2013</h5>");
        contents.append("</footer>");
        contents.append("</div>");
        contents.append("</body></html>");
        // 描画する
        response.getWriter().print(contents.toString());
    }

    @Override
    protected AuthorizationCodeFlow initializeFlow() throws ServletException,
            IOException {
        return Utility.initializeFlow();
    }

    @Override
    protected String getRedirectUri(HttpServletRequest request)
            throws ServletException, IOException {
        return Utility.getRedirectUri(request);
    }

    private List<String[]> getCalendarList(
            com.google.api.services.calendar.Calendar cal) throws IOException {
        List<String[]> calendarList = Lists.newArrayList();
        String[] calendar = new String[4];
        com.google.api.services.calendar.model.CalendarList cl = cal
                .calendarList().list().execute();
        while (true) {
            List<com.google.api.services.calendar.model.CalendarListEntry> clel = cl
                    .getItems();
            if (clel != null) {
                for (com.google.api.services.calendar.model.CalendarListEntry cle : clel) {
                    // カレンダー名の取得
                    String id = cle.getId();
                    String summary = cle.getSummary();
                    summary = summary == null ? "" : summary;
                    // リストに追加
                    calendar = new String[] { id, summary };
                    calendarList.add(calendar);
                }
            }
            String token = cl.getNextPageToken();
            if (token != null && !token.isEmpty()) {
                cl = cal.calendarList().list().setPageToken(token).execute();
            } else {
                break;
            }
        }
        return calendarList;
    }

}
